/**
 * Created by tanbingqin on 2018/12/20.
 */
import React from 'react'
import { connect } from 'react-redux'
import moment from 'moment'
import constants from 'share/constants'
import {messages, getApprovelHistory, getQueryUrlParam, queryCurrencyPrecision} from 'share/common'
import { Form, Tabs, Affix, Spin, Row, message, Alert } from 'antd'
import otherService from 'containers/approve/other/other.service'
import 'styles/approve/other/other.scss'
import ApproveHistory from 'components/template/approve-history'
import ApproveTag from 'components/template/approve-tag'
import customField from 'share/customField'
import GoBackBtn from 'containers/approve/other/btns/go-back-btn'
import ApproveOtherBtn from 'containers/approve/other/btns/approve-other-btn'

const TabPane = Tabs.TabPane;

class OtherDetail extends React.Component{
  constructor(props) {
    super(props);
    this.state = {
      tabValue: 'otherInfo',
      loading: false,
      formOID: '',
      formType: '',
      formInfo: {},
      info: {}, //其他单详情
      approvalHistory: [], //审批历史
    }
  }

  componentDidMount() {
    this.setState({
      formOID: this.props.params.formOID,
      approve: this.props.location.pathname.indexOf('approve-other-detail') > -1
    },() => {
      const { approve } = this.state;
      this.setState({
        readOnly: approve || this.props.location.query.readOnly
      });
      this.getFormType(this.state.formOID);
    })
  }

  getFormType = (formOID) => {
    this.setState({ loading: true });
    otherService.getFormType(formOID).then(res => {
      this.setState({
        formType: res.data.formType,
        formInfo: res.data
      },() => {
        this.getInfo(this.state.formType);
      });
    }).catch(e => {
      this.setState({loading: false});
      let error = e.response.data;
      if (error.validationErrors && error.validationErrors.length) {
        message.error(error.validationErrors[0].message);
      } else {
        message.error(error.message);
      }
    })
  };

  getInfo = () => {
    //formType：2001（差旅申请）、2002（费用申请）、2003（订票申请）、2004（京东申请）、2005（借款申请）
    const { entityOID } = this.props.params;
    this.setState({ loading: true });
    otherService.getOtherDetail(entityOID).then(res => {
      this.setState({
        loading: false,
        info: res.data,
        approvalHistory: res.data.approvalHistorys
      },() => {
        if (this.state.approve) {
          let info = this.state.info;
          this.setState({showApproveBottom: this.showApproveButton(info.approvalChain, info.approvalChains, this.props.user.userOID, info.status)});
        }
      });
    }).catch(e => {
      this.setState({loading: false});
      let error = e.response.data;
      if (error.validationErrors && error.validationErrors.length) {
        message.error(error.validationErrors[0].message)
      } else {
        message.error(error.message)
      }
    })
  };

  //判断是否显示底部审批／驳回等按钮
  showApproveButton = (approvalChain, approvalChains, currentUserId, status) => {
    let showBottom = false;
    if(status !== 1002){
      return;
    }
    if(approvalChain){
      if(approvalChain.approverOID == currentUserId){
        showBottom = true;
      }
    }
    if(approvalChains){
      approvalChains.forEach((approver) => {
        if(approver.approverOID == currentUserId){
          showBottom = true;
        }else{
          if(approver.proxyApproverOIDs){
            approver.proxyApproverOIDs.forEach((proxyApprover) => {
              if(proxyApprover == currentUserId){
                showBottom = true;
              }
            })
          }
        }
      })
    }
    return showBottom;
  };

  //其他单信息／审批进度 切换
  handleTabsChange = (tab) => {
    this.setState({ tabValue: tab });
  };

  render() {
    const { approving } = this.props.location.query;
    const { loading, formType, formInfo, info, approvalHistory, approve, readOnly, showApproveBottom, tabValue} = this.state;
    let applicant = info.applicant || {}; //申请人信息
    let custFormValues = info.custFormValues || []; //自定义表单
    custFormValues.sort((a, b) => a.sequence > b.sequence || -1);
    let otherInfo = (
      <Spin spinning={loading}>
        <div className="top-info">
          <Row className="row-container">
            <span className="top-info-name">{applicant.fullName}</span>
            <span className="detail-info">
              {messages('request.key3'/*工号*/)}：{applicant.employeeID}
              <span className="ant-divider"/>
              {messages('request.key4'/*部门*/)}：{applicant.departmentName || '-'}
              <span className="ant-divider"/>
              {messages('common.user.company')/*员工公司*/}：{applicant.companyName || '-'}
            </span>
          </Row>
          <Row className="row-container">
            <span className="detail-info detail-info-first">{info.formName}：{info.businessCode}</span>
            <span className="detail-info">
              {messages('request.key5'/*提交日期*/)}：{moment(info.submittedDate).format('YYYY-MM-DD')}
            </span>
          </Row>
        </div>
      </Spin>
    );
    let detailContent = (
      <Spin spinning={loading}>
        <div className="tab-container">
          <h3 className="sub-header-title">{messages('approve.key117')/*单据详情*/}</h3>
          {customField.renderFields(custFormValues, info, applicant)}
        </div>
      </Spin>
    );
    return (
      <div className="other-detail background-transparent">
        <div className="tabs-info" style={{position: 'relative'}}>
          <Tabs type="card" activeKey={tabValue} onChange={this.handleTabsChange}>
            <TabPane tab={messages('approve.key118')/*单据信息*/} key="otherInfo">{otherInfo}</TabPane>
            <TabPane tab={messages('request.key12'/*审批历史*/)} key="approvals">
              <ApproveHistory approvalChains={info.approvalChains} businessCode={info.businessCode} approvalHistory={approvalHistory} applicantInfo={applicant}/>
            </TabPane>
          </Tabs>
          {!!approving && !readOnly && showApproveBottom && (
            <ApproveTag entityOID={this.props.params.entityOID}/>
          )}
        </div>
        {tabValue === 'otherInfo' && (
          <div className="detail-tabs">{detailContent}</div>
        )}
        {(!readOnly || approve) && (
          <Affix offsetBottom={0} className={`bottom-bar ${((approve && approving && showApproveBottom) || (!approve && approving)) ? 'bottom-bar-approve' : ''}`}>
            {!readOnly && <GoBackBtn backType={this.props.params.backType}/>}
            {approve && <ApproveOtherBtn formType={Number(formType)} info={info} approving={!!approving && showApproveBottom} formInfo={formInfo} backUrlKey={getQueryUrlParam('backUrlKey')}/>}
          </Affix>
        )}
        {(readOnly && !approve) && (
          <Affix offsetBottom={0} className='bottom-bar'>
            <GoBackBtn/>
          </Affix>
        )}
      </div>
    )
  }
}

OtherDetail.contextTypes = {
  router: React.PropTypes.object
};

function mapStateToProps(state) {
  return {
    user: state.login.user
  }
}

const wrappedOtherDetail = Form.create()(OtherDetail);

export default connect(mapStateToProps)(wrappedOtherDetail)
